/**
 * Created by XianTao on 2016/11/14
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.aes.aop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.lego.util.HttpUtil;
import org.lego.wechat.base.entity.WxCorp;
import org.lego.wechat.base.service.WxCorpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Order(10)
@Aspect
@Component
@Slf4j
public class WechatAesAspect {
    @Autowired
    private WxCorpService wxCorpService;

    @Pointcut("execution(* org.lego.wechat.portal.restful.WechatPortalRestful.processRequest(..))")
    public void wechatAes() {
    }

    @Around("wechatAes()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String originalMessage = HttpUtil.readIncommingRequestData(request);
        log.info("接收到的加密消息：\n{}", originalMessage);

        WxCorp corp = wxCorpService.findOne("1");
//        try {
//            String message = WxMsgCryptKit.create(corp.getToken(), corp.getEncodingAesKey(), corp.getCorpId())
//                    .decryptMsg(HttpUtil.getPara("msg_signature", request),
//                            HttpUtil.getPara("timestamp", request),
//                            HttpUtil.getPara("nonce", request),
//                            originalMessage);
        String message = originalMessage;
        request.getSession().setAttribute("wechat_message", message);
//        } catch (WxAesException e) {
//            log.error("WxAesException: {}", e.getMessage());
//            throw new RuntimeException(e);
//        }

        Object ret = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());

//        String replyMessage = WxMsgCryptKit.create(corp.getToken(), corp.getEncodingAesKey(), corp.getCorpId())
//                    .encryptMsg(String.valueOf(ret), null, HttpUtil.getPara("nonce", request));
        String replyMessage = String.valueOf(ret);
        log.info("应答的加密消息：\n{}", replyMessage);
        return replyMessage;
    }
}
